// 对数组扁平化、去重后、并排序
const arr = [8, 1, [2, 5, 1, 3], 2, 2, [6], 3, 3, 4, [4, 3, [5, 4], 7]];
Array.prototype.reduce2 = function (callback, acc) {
  let startIndex = 0
  if (acc === undefined) {
    acc = this[0]
    startIndex = 1
  }
  for (let i = startIndex; i < this.length; i++) {
    acc = callback(acc, this[i], i)
  }
  return acc
}

Array.prototype.flat2 = function (deep = 1) {
  if (deep <= 0) return this
  return this.reduce2((acc, cur) => {
    return acc.concat(Array.isArray(cur) ? cur.flat2(deep - 1) : cur)
  }, [])
}

Array.prototype.unique2 = function () {
  for (let i = 0; i < this.length; i++) {
    for (let j = i + 1; j < this.length; j++) {
      if (this[i] === this[j]) {
        this.splice(j, 1)
        j--
      }
    }
  }
  return this
}

Array.prototype.sort2 = function (callback) {
  // 外层：趟，this.length - 1
  // 内层：次，this.length - 1 - i
  for (let i = 0; i < this.length - 1; i++) {
    let flag = true // 已经排列好啦
    for (let j = 0; j < this.length - i - 1; j++) {
      // if(this[j] > this[j + 1]) {
      if (callback(this[j], this[j + 1]) > 0) {
        [this[j], this[j + 1]] = [this[j + 1], this[j]]
        flag = false
      }
    }
    if (flag) break;
  }
  return this
}

// Array.from
const r = arr.flat2(Infinity).unique2().sort2((prev, next) => prev - next)
console.log(r)
